﻿using System;
using System.Text;
using System.Linq;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using Data;
using EuphoricNation.Util;

namespace EuphoricNation.Page
{
    public class EuphoricNationPage : System.Web.UI.Page
    {
        private EuphoricNationEntities _context;

        private Dictionary<string, string> _params = null;

        private string _keywords;
        private string _description;

        private bool _index = true;
        private bool _follow = true;
        private bool _noOdp = true;
        private bool _noYdir = true;
        private bool _fixAction = true;

        public EuphoricNationPage()
        {
            Page.PreRender += new EventHandler(BasePage_PreRender);
        }

        protected void BasePage_PreRender(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(_description))
                SetDescriptionTag();

            if (!string.IsNullOrEmpty(_keywords))
                SetKeywordsTag();

            SetRobots();

            if (FixAction)
                Form.Action = Request.Path;
        }

        public override void Dispose()
        {
            base.Dispose();

            if (_context != null && !_context.IsDisposed)
                _context.Dispose();
        }

        public void ClearContext()
        {
            if (_context != null && !_context.IsDisposed)
                _context.Dispose();

            _context = new EuphoricNationEntities();
        }

        private void SetKeywordsTag()
        {
            HtmlMeta tag = new HtmlMeta();
            tag.Name = "keywords";
            tag.Content = _keywords;
            Page.Header.Controls.Add(tag);
        }

        private void SetDescriptionTag()
        {
            HtmlMeta tag = new HtmlMeta();
            tag.Name = "description";
            tag.Content = _description;
            Page.Header.Controls.Add(tag);
        }

        private void SetRobots()
        {
            Literal lrl = new Literal();
            StringBuilder output = new StringBuilder("<meta name=\"robots\" content=\"");

            if (_index)
                output.Append("INDEX, ");
            else
                output.Append("NOINDEX, ");

            if (_follow)
                output.Append("FOLLOW");
            else
                output.Append("NOFOLLOW");

            if (_noOdp)
                output.Append(", NOODP");

            if (_noYdir)
                output.Append(", NOYDIR");

            output.Append("\" />");

            lrl.EnableViewState = false;
            lrl.Text = output.ToString();
            Page.Header.Controls.Add(lrl);
        }

        public void SetPageInfo<T>(T content) where T : ContentBase
        {
            if (content != null)
            {
                Title = content.SEOTitle;
                Description = content.SEODescription;
                Keywords = content.SEOKeywords;
            }
        }

        public void SetPageInfo(string title, string description, string keywords)
        {
            Title = title;
            Description = description;
            Keywords = keywords;
        }

        /// <summary>
        /// DataContext for interacting with database
        /// </summary>
        public EuphoricNationEntities DataContext
        {
            get
            {
                if (_context == null || _context.IsDisposed)
                    _context = new EuphoricNationEntities();

                return _context;
            }
        }

        /// <summary>
        /// What are the keywords for this page?
        /// </summary>
        public string Keywords
        {
            get { return _keywords; }
            set { _keywords = string.Format("Euphoric,Nation, {0}", value); }
        }

        /// <summary>
        /// What is the description for this page?
        /// </summary>
        public string Description
        {
            get { return _description; }
            set { _description = value; }
        }

        /// <summary>
        /// Should robots index this page?
        /// </summary>
        public bool Index
        {
            get { return _index; }
            set { _index = value; }
        }

        /// <summary>
        /// Should robots follow the links on this page?
        /// </summary>
        public bool Follow
        {
            get { return _follow; }
            set { _follow = value; }
        }

        /// <summary>
        /// Disallow usage of Open Directory Project titles
        /// </summary>
        public bool NoODP
        {
            get { return _noOdp; }
            set { _noOdp = value; }
        }

        /// <summary>
        /// Disallow usage of Yahoo directory titles
        /// </summary>
        public bool NoYDIR
        {
            get { return _noYdir; }
            set { _noYdir = value; }
        }

        /// <summary>
        /// Whether to fix the form 'Action' attribute to the correct address
        /// </summary>
        public bool FixAction
        {
            get { return _fixAction; }
            set { _fixAction = value; }
        }

        public Dictionary<string, string> QueryParameters
        {
            get
            {
                // Lazy-load
                if (_params != null)
                    return _params;
                else
                {
                    string[] pathParts = Request.Path.Split('/');
                    bool qFound = false;
                    _params = new Dictionary<string, string>();

                    if (pathParts.Length > 0)
                    {
                        for (int i = 0; i < pathParts.Length - 1; ++i)
                        {
                            if (pathParts[i] == "q" || qFound)
                            {
                                _params[pathParts[i]] = pathParts[++i];
                                qFound = true;
                            }
                        }
                    }

                    return _params;
                }
            }
        }

        /// <summary>
        /// Parameters specified by rewrite engine
        /// </summary>
        public Dictionary<string, string> RewriteParameters
        {
            get
            {
                if (Context.Items[Constants.KEY_SHAREDCONTEXT_GETVARS] != null)
                    return (Dictionary<string, string>)Context.Items[Constants.KEY_SHAREDCONTEXT_GETVARS];
                else
                    return new Dictionary<string, string>();
            }
        }
    }
}